// pages/verification/verification.js
const { get, post } = require('../../utils/api.js')
const { showError, showSuccess, showToast } = require('../../utils/util.js')

Page({
  data: {
    // 验证状态
    verificationStatus: {
      realName: 'none', // none, pending, approved, rejected
      education: 'none',
      occupation: 'none'
    },
    
    // 验证表单数据
    formData: {
      realName: {
        fullName: '',
        idNumber: '',
        idCardFront: '',
        idCardBack: ''
      },
      education: {
        school: '',
        major: '',
        degree: '',
        graduationYear: '',
        certificate: ''
      },
      occupation: {
        company: '',
        position: '',
        workYears: '',
        workProof: '',
        workEmail: ''
      }
    },
    
    // UI状态
    activeTab: 'realName',
    loading: false,
    uploading: false,
    
    // 选项数据
    degreeOptions: [
      { label: '高中', value: 'highschool' },
      { label: '大专', value: 'college' },
      { label: '本科', value: 'bachelor' },
      { label: '硕士', value: 'master' },
      { label: '博士', value: 'doctor' }
    ],
    
    workYearsOptions: [
      { label: '应届毕业生', value: '0' },
      { label: '1年以下', value: '0-1' },
      { label: '1-3年', value: '1-3' },
      { label: '3-5年', value: '3-5' },
      { label: '5-10年', value: '5-10' },
      { label: '10年以上', value: '10+' }
    ],
    
    // 弹窗状态
    showDegreePopup: false,
    showWorkYearsPopup: false,
    showVerificationTip: false,
    
    // 验证说明
    verificationTips: {
      realName: '实名认证可以提高账号安全性，认证信息仅用于身份验证，严格保密。',
      education: '学历认证可以提高个人信用度，增加匹配成功率。',
      occupation: '职业认证有助于建立职业形象，获得更多关注。'
    }
  },

  onLoad() {
    this.loadVerificationStatus()
  },

  /**
   * 加载验证状态
   */
  loadVerificationStatus() {
    this.setData({ loading: true })
    
    get('/api/user/verification-status')
      .then(data => {
        this.setData({
          verificationStatus: { ...this.data.verificationStatus, ...data.status },
          formData: { ...this.data.formData, ...data.formData },
          loading: false
        })
      })
      .catch(error => {
        console.error('加载验证状态失败:', error)
        this.setData({ loading: false })
      })
  },

  /**
   * 切换Tab
   */
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab
    this.setData({ activeTab: tab })
  },

  /**
   * 表单输入处理
   */
  onFieldInput(e) {
    const { type, field } = e.currentTarget.dataset
    const value = e.detail.value
    
    this.setData({
      [`formData.${type}.${field}`]: value
    })
  },

  /**
   * 选择学历
   */
  showDegreeSelector() {
    this.setData({ showDegreePopup: true })
  },

  onDegreeConfirm(e) {
    const degree = e.detail.value
    this.setData({
      'formData.education.degree': degree,
      showDegreePopup: false
    })
  },

  hideDegreePopup() {
    this.setData({ showDegreePopup: false })
  },

  /**
   * 选择工作年限
   */
  showWorkYearsSelector() {
    this.setData({ showWorkYearsPopup: true })
  },

  onWorkYearsConfirm(e) {
    const workYears = e.detail.value
    this.setData({
      'formData.occupation.workYears': workYears,
      showWorkYearsPopup: false
    })
  },

  hideWorkYearsPopup() {
    this.setData({ showWorkYearsPopup: false })
  },

  /**
   * 图片上传
   */
  uploadImage(e) {
    const { type, field } = e.currentTarget.dataset
    
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.handleImageUpload(res.tempFilePaths[0], type, field)
      },
      fail: (error) => {
        console.error('选择图片失败:', error)
        showError('选择图片失败')
      }
    })
  },

  /**
   * 处理图片上传
   */
  handleImageUpload(tempFilePath, type, field) {
    this.setData({ uploading: true })
    
    wx.uploadFile({
      url: `${getApp().globalData.apiBase}/api/upload/verification`,
      filePath: tempFilePath,
      name: 'file',
      formData: {
        type: type,
        field: field
      },
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        try {
          const data = JSON.parse(res.data)
          if (data.success) {
            this.setData({
              [`formData.${type}.${field}`]: data.fileUrl,
              uploading: false
            })
            showSuccess('上传成功')
          } else {
            throw new Error(data.message || '上传失败')
          }
        } catch (error) {
          console.error('上传响应解析失败:', error)
          showError('上传失败，请重试')
          this.setData({ uploading: false })
        }
      },
      fail: (error) => {
        console.error('上传失败:', error)
        showError('上传失败，请检查网络')
        this.setData({ uploading: false })
      }
    })
  },

  /**
   * 预览图片
   */
  previewImage(e) {
    const url = e.currentTarget.dataset.url
    if (url) {
      wx.previewImage({
        urls: [url],
        current: url
      })
    }
  },

  /**
   * 删除图片
   */
  deleteImage(e) {
    const { type, field } = e.currentTarget.dataset
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这张图片吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            [`formData.${type}.${field}`]: ''
          })
        }
      }
    })
  },

  /**
   * 提交验证
   */
  submitVerification(e) {
    const type = e.currentTarget.dataset.type
    
    if (!this.validateForm(type)) {
      return
    }
    
    const submitData = this.data.formData[type]
    
    this.setData({ loading: true })
    
    post(`/api/user/verification/${type}`, submitData)
      .then(response => {
        showSuccess('提交成功，请等待审核')
        
        // 更新验证状态
        this.setData({
          [`verificationStatus.${type}`]: 'pending',
          loading: false
        })
        
        // 延迟刷新状态
        setTimeout(() => {
          this.loadVerificationStatus()
        }, 2000)
      })
      .catch(error => {
        console.error('提交验证失败:', error)
        showError('提交失败，请重试')
        this.setData({ loading: false })
      })
  },

  /**
   * 表单验证
   */
  validateForm(type) {
    const data = this.data.formData[type]
    
    switch (type) {
      case 'realName':
        if (!data.fullName.trim()) {
          showError('请输入真实姓名')
          return false
        }
        if (!data.idNumber.trim()) {
          showError('请输入身份证号码')
          return false
        }
        if (!/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(data.idNumber)) {
          showError('身份证号码格式不正确')
          return false
        }
        if (!data.idCardFront) {
          showError('请上传身份证正面照片')
          return false
        }
        if (!data.idCardBack) {
          showError('请上传身份证背面照片')
          return false
        }
        break
        
      case 'education':
        if (!data.school.trim()) {
          showError('请输入学校名称')
          return false
        }
        if (!data.major.trim()) {
          showError('请输入专业名称')
          return false
        }
        if (!data.degree) {
          showError('请选择学历')
          return false
        }
        if (!data.graduationYear.trim()) {
          showError('请输入毕业年份')
          return false
        }
        if (!/^\d{4}$/.test(data.graduationYear)) {
          showError('毕业年份格式不正确')
          return false
        }
        break
        
      case 'occupation':
        if (!data.company.trim()) {
          showError('请输入公司名称')
          return false
        }
        if (!data.position.trim()) {
          showError('请输入职位名称')
          return false
        }
        if (!data.workYears) {
          showError('请选择工作年限')
          return false
        }
        if (!data.workEmail.trim()) {
          showError('请输入工作邮箱')
          return false
        }
        if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.workEmail)) {
          showError('工作邮箱格式不正确')
          return false
        }
        break
    }
    
    return true
  },

  /**
   * 显示验证说明
   */
  showTip(e) {
    const type = e.currentTarget.dataset.type
    const tip = this.data.verificationTips[type]
    
    wx.showModal({
      title: '验证说明',
      content: tip,
      showCancel: false,
      confirmText: '我知道了'
    })
  },

  /**
   * 获取验证状态文本
   */
  getStatusText(status) {
    const statusMap = {
      'none': '未认证',
      'pending': '审核中',
      'approved': '已认证',
      'rejected': '认证失败'
    }
    return statusMap[status] || '未知状态'
  },

  /**
   * 获取验证状态样式
   */
  getStatusClass(status) {
    const classMap = {
      'none': 'status-none',
      'pending': 'status-pending',
      'approved': 'status-approved',
      'rejected': 'status-rejected'
    }
    return classMap[status] || 'status-none'
  },

  /**
   * 返回上一页
   */
  goBack() {
    wx.navigateBack()
  }
})